/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elookinto.wordlist;

import java.util.Date;
import java.util.Iterator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
import java.util.TreeSet;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.io.IOUtils;

public class SendMail {

    static String host, port, emailid,username, password;
    Properties props = System.getProperties();
    Session l_session = null;
    static Session session;
    public SendMail() {
        host = "smtp.mail.yahoo.com";
        port = "587";
        emailid = "zwu_ca@yahoo.com";
        username = "zwu_ca";
        password = "liliping01";

        emailSettings();
        createSession();
        //sendMessage("a@yahoo.com", "rahul@gmail.com","Test","test Mail");
    }

    public void emailSettings() {
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "false");
        props.put("mail.smtp.port", port);
//        props.put("mail.smtp.socketFactory.port", port);
//        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.put("mail.smtp.socketFactory.fallback", "false");

    }

    public void createSession() {

        session=l_session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        l_session.setDebug(true); // Enable the debug mode

    }

    public boolean sendMessage(String emailFromUser, String toEmail, String subject, String msg) {
        //System.out.println("Inside sendMessage 2 :: >> ");
        try {
            //System.out.println("Sending Message *********************************** ");
            MimeMessage message = new MimeMessage(l_session);
            emailid = emailFromUser;
            //System.out.println("mail id in property ============= >>>>>>>>>>>>>> " + emailid);
            //message.setFrom(new InternetAddress(emailid));
            message.setFrom(new InternetAddress(this.emailid));

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
//            message.addRecipient(Message.RecipientType.BCC, new InternetAddress(AppConstants.fromEmail));
            message.setSubject(subject);
            message.setContent(msg, "text/html");

            //message.setText(msg);
            Transport.send(message);
            System.out.println("Message Sent");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }//end catch block
        return true;
    }
    
    
    
    public static void main(String[] args)
  {

      SendMail sm = new SendMail();
     Properties props = new Properties();

    String host1      =  "imap.mail.yahoo.com"; //host;//args[0];
    String username1  = "zwu_ca@yahoo.com"; //username; //args[1];
    String password1  =password; // args[2];
    //String provider  = "pop3";
    String provider  = "imaps";

    try
    {
        props.setProperty("mail.store.protocol", "imaps");
      //Connect to the server
      Session session = Session.getDefaultInstance(props, null);
      Store store     = session.getStore(provider);
      store.connect(host1, username1, password1);

      //open the inbox folder
      Folder inbox = store.getFolder("testingmom");
      inbox.open(Folder.READ_ONLY);

      // get a list of javamail messages as an array of messages
      Message[] messages = inbox.getMessages();

      TreeSet treeSet = new TreeSet();

      for(int i = 0; i < Math.min(messages.length, 10); i++)
      {
          String subj = messages[i].getSubject();
          Date d = messages[i].getReceivedDate();
         String message =  IOUtils.toString(messages[i].getInputStream(), "UTF-8");
         if (subj.contains("Question")){
          System.out.println(subj +"...."+ d);
          int b = message.indexOf("<html dir");
          int e = message.indexOf("</html>", b);
           if (b>0 && e>0)
          System.out.println(message.substring(b, e+7));
         }
                  ;
        /*String from = getFrom(messages[i]);
        if ( from!=null)
        {
          from = removeQuotes(from);
          treeSet.add(from);
        }*/
      }

      Iterator it = treeSet.iterator();
      while ( it.hasNext() )
      {
        System.out.println("from: " + it.next());
      }

      //close the inbox folder but do not
      //remove the messages from the server
      inbox.close(false);
      store.close();
    }
    catch (NoSuchProviderException nspe)
    {
      System.err.println("invalid provider name");
    }
    catch (MessagingException me)
    {
      System.err.println("messaging exception");
      me.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
  }

  private static String getFrom(Message javaMailMessage) 
  throws MessagingException
  {
    String from = "";
    Address a[] = javaMailMessage.getFrom();
    if ( a==null ) return null;
    for ( int i=0; i<a.length; i++ )
    {
      Address address = a[i];
      from = from + address.toString();
    }

    return from;
  }

  private static String removeQuotes(String stringToModify)
  {
    int indexOfFind = stringToModify.indexOf(stringToModify);
    if ( indexOfFind < 0 ) return stringToModify;

    StringBuffer oldStringBuffer = new StringBuffer(stringToModify);
    StringBuffer newStringBuffer = new StringBuffer();
    for ( int i=0, length=oldStringBuffer.length(); i<length; i++ )
    {
      char c = oldStringBuffer.charAt(i);
      if ( c == '"' || c == '\'' )
      {
        // do nothing
      }
      else
      {
        newStringBuffer.append(c);
      }

    }
    return new String(newStringBuffer);
  }
  
    /*public static void main(String s[])
    {
        SendMail sm = new SendMail();
        sm.sendMessage("zwu_ca@yahoo.com", "zwu_ca@yahoo.com", "java test", "test");
    }*/

}